package com.qire.manhua.model.viewModel.impl;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface.OnDismissListener;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import com.qire.antscore.annotation.PropertyObserve;
import com.qire.antsrouter.lifecycleHandler.ActivityManageHandler;
import com.qire.common.basic.ColorUtil;
import com.qire.common.basic.ObjectUtil;
import com.qire.common.basic.StringUtil;
import com.qire.common.collect.ListUtil;
import com.qire.common.collect.SafeIterableList;
import com.qire.common.collect.SafeIterableMap;
import com.qire.common.constant.AdvertManage;
import com.qire.common.model.entity.UserEntity;
import com.qire.common.support.DialogManage;
import com.qire.common.support.AbsBringDialogViewModel;
import com.qire.common.utils.EquipmentInfoUtil;
import com.qire.common.utils.ToastHelper;
import com.qire.common.widget.adapter.auto.AutoVariable;
import com.qire.common.widget.adapter.auto.SummerBindAdapter;
import com.qire.common.widget.adapter.auto.annotation.AdapterEntityBind;
import com.qire.common.widget.snackbar.Prompt;
import com.qire.manhua.BR;
import com.qire.manhua.R;
import com.qire.manhua.controller.ComicReaderController;
import com.qire.manhua.databinding.ActivityComicReaderBinding;
import com.qire.manhua.databinding.LayoutComicReaderItemBinding;
import com.qire.manhua.databinding.LayoutComicReaderItemCommentBinding;
import com.qire.manhua.dialog.TeensRestrictReadDialog;
import com.qire.manhua.dialog.UnlockChapterOnComicReaderDialog;
import com.qire.manhua.dal.service.ComicReaderService;
import com.qire.manhua.model.entity.BulletScreenInfo;
import com.qire.manhua.model.entity.ComicBookEntity;
import com.qire.manhua.model.entity.ComicBookEntity.DirectoryInfo;
import com.qire.manhua.model.entity.ComicBookEntity.ChaptersInfo;
import com.qire.manhua.model.entity.ComicComment;
import com.qire.manhua.model.entity.ShareInfo;
import com.qire.manhua.model.viewModel.IComicReaderViewModel;
import com.qire.manhua.view.FirstBuyCoinView;
import com.qire.manhua.view.animator.BottomFoldingAnimationBinder;
import com.qire.manhua.view.animator.TopFoldingAnimationBinder;
import com.qire.manhua.view.comicReader.ComicReaderView;
import com.qire.manhua.view.comicReader.renderer.PictureResource;

import java.util.ArrayList;
import java.util.HashMap;

import androidx.databinding.BaseObservable;
import androidx.databinding.Bindable;

/**
 * 漫画阅读页的ViewModel
 */
public class ComicReaderViewModel extends AbsBringDialogViewModel<IComicReaderViewModel> {

    /** 顶部导航菜单栏折叠动画 */
    private final TopFoldingAnimationBinder topNavBarAnimation = new TopFoldingAnimationBinder();

    /** 底部功能菜单栏折叠动画 */
    private final BottomFoldingAnimationBinder bottomMenuBarAnimation = new BottomFoldingAnimationBinder();

    /** 更多功能菜单栏折叠动画 */
    private final BottomFoldingAnimationBinder moreMenuBarAnimation = new BottomFoldingAnimationBinder();

    /** 漫画阅读器项目ViewModel列表 */
    private final ArrayList<ComicReaderItemViewModel> comicReaderItemList = new ArrayList<>();

    /** 漫画阅读器ListView适配器*/
    private final SummerBindAdapter<ComicReaderItemViewModel> loopComicReaderViewAdapter = new SummerBindAdapter(comicReaderItemList, R.layout.layout_comic_reader_item);

    /** 漫画阅读model service */
    private ComicReaderService comicReaderService = new ComicReaderService(this);

    /** 漫画实体模型 */
    private ComicBookEntity comicBookEntity;

    /** 漫画阅读器交互事件控制器 */
    private ComicReaderController controller;

    /** 漫画阅读器页面数据绑定器 */
    private ActivityComicReaderBinding viewDataBinder;

    /** 分享信息实体模型 */
    private ShareInfo shareInfo = null;

    /** 记录已读章节ID，用于统计已经阅读了多少章节，以便后续业务逻辑中使用 */
    private ArrayList<Integer> haveReadChapterIdList = new ArrayList<>();

    /**
     * 是否已准备退出当前页
     */
    private boolean isFinish = false;

    public ComicReaderViewModel() {
        super();

        //
        set("loopComicReaderViewAdapter", loopComicReaderViewAdapter);
        set("topNavBarAnimation", topNavBarAnimation);
        set("bottomMenuBarAnimation", bottomMenuBarAnimation);
        set("moreMenuBarAnimation", moreMenuBarAnimation);

        hideFavoritePrompt();

    }

    //region    #附加管理 begin
    /**
     * 附加属性绑定
     * @param controller 事件控制器
     */
    public void onAddition(ComicReaderController controller, ActivityComicReaderBinding viewDataBinder) {
        this.controller = controller;
        this.viewDataBinder = viewDataBinder;

        loopComicReaderViewAdapter.setEventProcess(controller);
    }

    /**
     * 清理函数，在Activity退出时，ViewModel生命周期到期会被回收，调用该事件，页面由于切换、横竖屏转换、内存回收等情况并不会影响到ViewModel的生命周期。
     */
    @Override
    protected void onCleared() {
        super.onCleared();
        // todo 由于关闭页面时会触发人气数据统计上报，但此处回收了漫画对象会导致空指针异常，简单修复需要其他解决方案来规避
//        this.comicBookEntity = null;
        this.viewDataBinder = null;
        this.controller = null;

        loopComicReaderViewAdapter.setEventProcess(null);
    }
    //endregion #附加管理 end

    //region    #业务逻辑 begin

    /**
     * 加载漫画书，ViewModel会持有并保存ComicBookEntity，并且通知Model加载漫画数据
     * @param comicBookEntity 漫画书实体
     */
    public void loadComicBook(ComicBookEntity comicBookEntity) {
        this.comicBookEntity = comicBookEntity;
        comicReaderService.loadComicDirectory();
        refreshFavoriteBtnUI();
    }

    /**
     * 漫画书实例
     * @return
     */
    public ComicBookEntity comicBookEntity(){
        return comicBookEntity;
    }

    /**
     * 通过目录索引查找章节
     * @param directoryIndex 目录索引
     * @return 章节
     */
    public ChaptersInfo findChapterBy(int directoryIndex) {
        if(comicBookEntity == null) {
            return null;
        }
        DirectoryInfo directoryInfo = comicBookEntity.findDirectoryInfo(directoryIndex);

        if(directoryInfo == null) {
            return null;
        }

        return directoryInfo.chaptersInfo;
    }

    /**
     * 检查章节是否需要解锁
     * @param chaptersInfo 章节
     * @return 需要提示检索则返回 true 否则 false
     */
    public boolean needUnlock(ChaptersInfo chaptersInfo) {
        return chaptersInfo.needUnlock() && comicBookEntity.lockInfo().needFirstUnlock();
    }

    /**
     * 预读指定章节
     * @return 章节为空则会阅读失败返回 false，否则阅读成功返回 true
     */
    public boolean preReadChapterBy(ChaptersInfo preReadingChapter) {

        if (preReadingChapter == null) {
            return false;
        }

        if (preReadingChapter.notLoaded()) {
            comicReaderService.preInstallComicChaptersInfo(preReadingChapter.id);
        }

        return true;
    }

    /**
     * 阅读指定的章节：
     * 1.修改当前展示标题；
     * 2.阅读章节，并且判定是否已读过，
     * 3.检查章节是否可读，如果需要解锁，则转到预装载流程
     * 4.如果未读则调用服务加载当前漫画，并且漫画阅读统计加1
     * 5.如果漫画阅读统计为限定次数且为被收藏则显示提示收藏横幅，目前次数限定为4次。
     * @param readingChapter 准备阅读的章节
     * @return 章节为空或漫画为空则会阅读失败返回 false，否则阅读成功返回 true
     */
    public boolean readChapterBy(ChaptersInfo readingChapter) {

        if(readingChapter == null) {
            return false;
        }

        if(comicBookEntity == null) {
            return false;
        }

        put("title", readingChapter.directoryInfo().chapterName);

        comicBookEntity.chaptersReading(readingChapter);

        if(needUnlock(readingChapter)) {
            preReadChapterBy(readingChapter);
            comicReaderService.updateReadHistory(readingChapter.id);
            /**
             * 章节内容在一次阅读内大致可看做不会变化的，所以避免以读章节重复调用接口，
             * 构造一个自动锁 readingChapter.haveRead() 会在首次调用后进入已读锁定状态。
             * 如果未解锁章节时调用 readingChapter.haveRead() 按照下面的逻辑，章节数据将停留在未解锁的不完整数据状态。
             * 所以未解锁状态不能触发 readingChapter.haveRead()，固再此返回，预读接口并不会触发服务器记录历史，所以需要掉一次更新阅读历史接口。
             * */
            return true;
        }

        if(!readingChapter.haveRead()) {
            comicReaderService.installComicChaptersInfo(readingChapter.id);
        }

        showFavoritePromptIfAllow(readingChapter.id);

        return true;
    }

    /**
     * 通过章节ID查找ItemViewModel
     * @param chaptersId 章节ID
     * @return ComicReaderItemViewModel 不存在ID相同则返回null
     */
    public ComicReaderItemViewModel findComicReaderItemViewModel(int chaptersId) {
        for(ComicReaderItemViewModel itemModel : comicReaderItemList) {
            if(itemModel.chaptersInfo.id == chaptersId) {
                return itemModel;
            }
        }
        return null;
    }

    /**
     * 添加循环阅读器章节项目ViewModel
     * @param chaptersInfo 章节信息实例
     */
    public void addComicReaderItem(ChaptersInfo chaptersInfo) {
        comicReaderItemList.add(new ComicReaderItemViewModel(chaptersInfo));
    }

    /**
     * 刷新循环阅读器数据
     */
    public void refreshComicReaderView() {
        loopComicReaderViewAdapter.notifyDataSetChanged();
    }

    /**
     * 通过购买解锁准备阅读的章节
     */
    public void unlockReadyReadChapterByBuy(int chapterId, String chapterPrice, String paymentType) {
        int comicId = comicBookEntity.id;
        int autoPay = UserEntity.self.isAutoPay() ? 1 : 0;
        comicReaderService.unlockChapterByBuy(comicId, chapterId, chapterPrice, paymentType, autoPay);
    }

    /**
     * 通过观看广告解锁准备阅读的章节
     */
    public void unlockReadyReadChapterByAd(int chapterId) {
        comicBookEntity.chaptersPreInstalled(chapterId).directoryInfo().unlock3Days();
        int comicId = comicBookEntity.id;
        comicReaderService.unlockChapterByAd(comicId, chapterId);
    }

    /**
     * 是否收藏，如果是收藏状态则会切换为取消收藏，反之亦然
     */
    public void whetherToFavorites(boolean isFinish) {
        this.isFinish = isFinish;
        comicReaderService.whetherJoinMyBookshelf(comicBookEntity);
    }

    /**
     * @return 分享信息
     */
    public ShareInfo shareInfo() {
        return shareInfo;
    }

    /**
     * 载入分享相信
     * @param shareInfo
     */
    public void loadShareInfo(ShareInfo shareInfo) {
        this.shareInfo = shareInfo;
    }

    /**
     * 如果达到条件 已阅读4个章节，则显示收藏提示栏
     * @param chapterId 当前阅读章节ID
     */
    public void showFavoritePromptIfAllow(int chapterId) {
        if(!haveReadChapterIdList.contains(chapterId)) {
            haveReadChapterIdList.add(chapterId);
        }
        boolean allowShow = haveReadChapterIdList.size() == 3;
        if(allowShow && !comicBookEntity.whetherCollect()) {
            showFavoritePrompt();
            return;
        }
    }

    /**
     * 本次进入阅读页是否已经读过章节
     * @return true 还未开始 false 已读过
     */
    public boolean notStartRead() {
        return ListUtil.isEmpty(haveReadChapterIdList);
    }

    /**
     * 检查首充福利，如果启用服务器则会开始限时计时，否则不开启只检查福利当前状态，
     * @param isEnable 是否启用激活，true 为启用， false 不启用
     */
    public void welfareCheck(boolean isEnable) {
        if (UserEntity.self.isLogin()) {
            comicReaderService.welfareCheck(isEnable);
        }
    }

    /**
     * 上报漫画人气数据
     */
    public void reportComicPopular(int scrollCount, int screenHeight, int comicHeight) {
        int bookId = comicBookEntity.id;
        int chapterId = comicBookEntity.currentReadingChapters().id;
        comicReaderService.reportComicPopular(bookId, chapterId, scrollCount, screenHeight, comicHeight);
    }

    public void gotoChapterBy(Context context, DirectoryInfo selectDirectory) {

        if(ObjectUtil.nonNull(selectDirectory) && selectDirectory.haveLock()) {

            UnlockChapterDialogViewModel unlockDialogViewModel = new UnlockChapterDialogViewModel();

            unlockDialogViewModel.loadComicData(comicBookEntity, selectDirectory);

//            readyItemModel.loadChaptersUnlockDialogViewModel(unlockDialogViewModel);

            boolean noInsufficientBalance = !unlockDialogViewModel.isInsufficientBalanceByPanel();
            boolean isAutoUnlock = UserEntity.self.isAutoPay();
            if(!(noInsufficientBalance && isAutoUnlock)){
                UnlockChapterOnComicReaderDialog unlockDialog = fetchChaptersUnlockDialog(context, unlockDialogViewModel);
                if(!unlockDialog.isShowing()) {
                    unlockDialog.show();
                }
                return;
            }
        }

        int chaptersPosition = comicBookEntity.getChaptersPositionByChapterId(selectDirectory.chapterId);

        proxy().gotoChaptersPosition(chaptersPosition);
    }

    public void teensRestrictReadTips() {
        Activity activity = ActivityManageHandler.HANDLER.currentActivity();
        if(ObjectUtil.nonNull(activity)) {
            TeensRestrictReadDialog restrictReadDialog = new TeensRestrictReadDialog(activity);
            restrictReadDialog.setOnDismissListener(dialog -> activity.finish());
            restrictReadDialog.show();
        }
    }

    //endregion #业务逻辑 end

    //region    #弹幕相关 begin

    /**
     * 暂存弹幕信息，保留最近一次弹幕信息，以方便编辑和发送
     */
    private BulletScreenInfo bulletScreenInfo;

    /**
     * 最后一次弹幕编辑后停留的当前阅读页面
     */
    private ComicReaderView  bulletScreenComicReaderView;

    /**
     * 提交添加弹幕：
     * 1.如果弹幕不存在，则不做任何操作；
     * 2.将弹幕提交到服务器；
     * 3.将弹幕插入于弹幕发送相关联的阅读器中。
     * 4.清除缓存弹幕信息。
     */
    public void submitBullet() {
        if(bulletScreenInfo == null || bulletScreenInfo.isEmpty()) {
            return;
        }

        comicReaderService.submitBullet(comicBookEntity, bulletScreenInfo);

        if(bulletScreenComicReaderView != null) {
            //todo 可能没有打开定位器，原有的逻辑可能被绕过，这样的情况弹幕可能发送在原点位置，
            bulletScreenComicReaderView.addBulletScreen(bulletScreenInfo.contentPictureToken(), bulletScreenInfo.toBulletScreen());
        }

        setBulletScreen(null);
    }

    /**
     * 设置弹幕，将弹幕暂时保存到缓存中，以便后续发送或编辑
     * @param bulletScreenInfo 弹幕信息
     */
    public void setBulletScreen(BulletScreenInfo bulletScreenInfo) {
        this.bulletScreenInfo = bulletScreenInfo;
        String bulletText = bulletScreenInfo == null ? "" : bulletScreenInfo.content;
        String bulletTextColor = bulletScreenInfo == null ? "#ffffff" : ColorUtil.RGB.from(bulletScreenInfo.fontColor()[0]);
        proxy().updateBulletText(bulletText, bulletTextColor);
        moveBulletScreenLocation();
    }

    /**
     * 定位弹幕：
     * 1.关联准备发送的弹幕到漫画阅读器View
     * 2.打开关联的漫画阅读器View弹幕移动定位器。（目前需求不需要定位直接发送了）
     */
    public void moveBulletScreenLocation() {
        if(bulletScreenInfo == null) {
            return;
        }

        bulletScreenComicReaderView = viewDataBinder.comicReaderListView.getReadingComicReaderView();

        if(bulletScreenComicReaderView != null) {
            bulletScreenComicReaderView.locateBulletScreen(bulletScreenInfo);
        }
    }

    //endregion #弹幕相关 end

    //region    #UI修改 begin
    public void setReadProgressText(int progress, int totalCount) {
        proxy().setReadProgressText(String.format("%sp/%sp", progress, totalCount));
    }

    /**
     * 显示Vip免费气泡提示，当Vip会员用户在观看VIP免费章节时弹出
     */
    public void showVipFreeToast() {
        if(!UserEntity.self.isVip()) {
            return;
        }

        DirectoryInfo directoryInfo = comicBookEntity.currentReadingDirectoryInfo();
        if(directoryInfo.isVipFree) {
            ToastHelper.showCustomToast(R.layout.toast_vip_free_tips);
        }
    }

    /**
     * 显示自动解锁提示Toast
     * @param title 提示标题
     * @param promptText 提示内容
     */
    public void showAutoUnlockToast(String title, String promptText){
        HashMap<Integer, String> viewModel = new HashMap<>();
        viewModel.put(R.id.autoToastTitle, title);
        viewModel.put(R.id.autoToastPromptText, promptText);
        HashMap<Integer, View.OnClickListener> controller = new HashMap<>();
//        controller.put(R.id.autoToastGoSetBtn, view -> SystemSetupActivity.start());
        ToastHelper.showCustomToast(R.layout.toast_auto_unlock_tips, Gravity.CENTER, viewModel, controller);
    }

    /**
     * 设置一个触摸监听到漫画阅读器，用在辅助控制
     * @param touchListener
     */
    public void setComicReaderOnTouch(OnTouchListener touchListener) {
        set("comicReaderOnTouch", touchListener);
    }

    /**
     * 切换上下菜单
     */
    public void toggleFoldingMenu() {
        if(topNavBarAnimation.toggle()) {
            bottomMenuBarAnimation.playIn();
        } else {
            bottomMenuBarAnimation.playOut();
        }
        moreMenuBarAnimation.playOut();
    }

    /**
     * 折叠上下菜单
     */
    public void foldingMenu() {
        topNavBarAnimation.playOut();
        bottomMenuBarAnimation.playOut();
        moreMenuBarAnimation.playOut();
    }

    /**
     * 切换底部菜单
     */
    public void toggleMoreMenu() {
        moreMenuBarAnimation.toggle();
        bottomMenuBarAnimation.toggle();
    }

    /**
     * 滑动漫画阅读器一个偏移量，用于点击屏幕上下滑动
     * @param offset 偏移距离
     */
    public void smoothScrollComicReader(int offset) {
        set("moveScrollOffset", offset);
    }

    /**
     * 翻页
     * @param down 下一页为 true ，上一页 false
     */
    public void pageTurning(boolean down) {
        if(comicBookEntity.canContinueNext(down)) {
            set("pageTurning", down);
        } else {
            String msg = down ? "已经是最后章节了" : "已经是第一章节了";
            ToastHelper.showSnackBar(msg, Prompt.WARNING);
        }
    }

    /**
     * 弹幕开关
     * @param off true 开启 false 关闭
     */
    public void bulletSwitch(boolean off) {
        proxy().bulletSwitch(off);
    }

    private void showToast(String msg) {
        if(isFinish) {
            ToastHelper.showSnackBarAtPreviousPage(msg, Prompt.SUCCESS);
        } else {
            ToastHelper.showSnackBar(msg, Prompt.SUCCESS);
        }
    }
    /**
     * 刷新收藏结果
     */
    public void refreshFavorite(String resultMsg, String takeMsg) {

        if(StringUtil.notContains(resultMsg, "失败")) {
            comicBookEntity.whetherCollect(StringUtil.notContains(resultMsg, "取消"));
        }

        refreshFavoriteBtnUI();

        showToast(resultMsg);

        if(StringUtil.notEmpty(takeMsg)) {
            showToast(takeMsg);
        }
        hideFavoritePrompt();
    }

    /**
     * 刷新底部菜单栏收藏按钮显示状态
     */
    public void refreshFavoriteBtnUI() {
        boolean whetherCollect = comicBookEntity == null ? false : comicBookEntity.whetherCollect();
        int iconRid = whetherCollect ? R.drawable.app_comic_reader_icon_bottom_collect_a : R.drawable.app_comic_reader_icon_bottom_collect_b;
        String text = whetherCollect ? "已收藏" : "收藏";
        proxy().setFavorites(iconRid, text);
    }

    /**
     * 显示"添加收藏夹提示"浮层视图
     */
    public void showFavoritePrompt() {
        set("favoritePromptVisible", View.VISIBLE);
    }

    /**
     * 隐藏"添加收藏夹提示"浮层视图
     */
    public void hideFavoritePrompt() {
        set("favoritePromptVisible", View.GONE);
    }

    /**
     * 阅读器章节解锁弹窗
     */
    private UnlockChapterOnComicReaderDialog unlockDialog;

    /**
     * 获取一个章节解锁弹窗，如果弹窗存在则返回已存在的。
     * @param unlockDialogViewModel 解锁信息ViewModel
     * @return 解锁弹窗
     */
    public UnlockChapterOnComicReaderDialog fetchChaptersUnlockDialog(Context context, UnlockChapterDialogViewModel unlockDialogViewModel) {
        return fetchChaptersUnlockDialog(context, unlockDialogViewModel,null);
    }

    /**
     * 获取一个章节解锁弹窗，如果弹窗存在则返回已存在的。
     * @param unlockDialogViewModel 解锁信息ViewModel
     * @param listener 退出事件回调
     * @return 解锁弹窗
     */
    public UnlockChapterOnComicReaderDialog fetchChaptersUnlockDialog(Context context, UnlockChapterDialogViewModel unlockDialogViewModel, OnDismissListener listener) {

        if(isShowUnlockDialog()) {
            return unlockDialog;
        }

        unlockDialog = UnlockChapterOnComicReaderDialog.build(context, unlockDialogViewModel, controller);

        unlockDialog.setOnDismissListener(dialog -> {
            unlockDialog = null;
            if(listener != null) {
                listener.onDismiss(dialog);
            }
            insertFirstBuyCoinViewToRoot(-1);
        });

        return unlockDialog;
    }

    private boolean isShowUnlockDialog() {
        return DialogManage.isShowing(unlockDialog);
    }

    /**
     * 新人特惠入口图标控件
     */
    private FirstBuyCoinView firstBuyCoinView;

    /**
     * 插入新人特惠入口图标控件：
     * 如果不存在则先构建控件然后再插入
     */
    public synchronized void insertFirstBuyCoinViewToRoot(long countdownTime) {
        ViewGroup viewGroup = isShowUnlockDialog() ? (ViewGroup) unlockDialog.getWindow().getDecorView() : (ViewGroup) viewDataBinder.getRoot();
        int bottomMargin = isShowUnlockDialog() ? EquipmentInfoUtil.dip2px(320) : EquipmentInfoUtil.dip2px(180);

        if(firstBuyCoinView == null) {
            firstBuyCoinView = FirstBuyCoinView.insertTo(viewGroup, countdownTime, bottomMargin);
            firstBuyCoinView.setOnClickListener(controller::firstBuyCoinViewOnClick);
        } else {
            firstBuyCoinView.injection(viewGroup,bottomMargin);
        }
    }

    /**
     * 从父控件中移除新人特惠入口图标控件
     */
    public synchronized void removeFirstBuyCoinViewToRoot() {
        if (firstBuyCoinView == null)
            return;
        firstBuyCoinView.setVisibility(View.GONE);
        firstBuyCoinView.removeFromParent();
    }

    //endregion #UI修改 end

    //region    #UI修改联动 begin

    @PropertyObserve(name = "bulletText")
    public void onBulletTextChange(String bulletText) {
        boolean isEmpty = StringUtil.isEmpty(bulletText);
        boolean sendBtnClickable = isEmpty ?  false : true;
        String sendBtnTextColor = isEmpty ? "#aeaeae" : "#ffffff";
        proxy().updateSendBulletBtn(sendBtnTextColor, sendBtnClickable);
    }

    //endregion #UI修改联动 end

    /**
     * 漫画阅读页 LoopComicReaderView 中子View的ViewModel，用来绑定适配器，为循环漫画阅读提供数据绑定
     */
    @AdapterEntityBind(viewRid = R.layout.layout_comic_reader_item)
    public class ComicReaderItemViewModel extends BaseObservable implements AutoVariable<LayoutComicReaderItemBinding> {

        private final ArrayList<ComicReaderCommentItemViewModel> commentList = new ArrayList();
        private final SummerBindAdapter commentAdapter = new SummerBindAdapter(commentList, controller);

        private final ChaptersInfo chaptersInfo;

        private int count = 0;
        private boolean isGiveLike = false;
        private boolean needShowAd = true;

        public ComicReaderItemViewModel(ChaptersInfo chaptersInfo) {
            this.chaptersInfo = chaptersInfo;
        }

        @Override
        public void bindVariable(LayoutComicReaderItemBinding viewBind) {
            viewBind.setComicReaderItemViewModel(this);

            // todo 滑动切换章节时卡顿可能来自 LoopComicReaderView 的滑动事件处理，需要注意在这里记录一下,这里由于广告加载报错，导致卡顿
            // java.lang.SecurityException: "network" location provider requires ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission.
            // at com.qire.manhua.view.comicReader.LoopComicReaderView.trackMotionScroll(LoopComicReaderView.java:566)
            if(needShowAd) { // 只请求一次
                needShowAd = false;
                AdvertManage.AdvertSpace.ComicBetween.readyAdvert().setAdvertContainer(viewBind.advertLayout);
            }
        }

        public int chapterId() {
            return chaptersInfo.id;
        }

        public void refreshUI() {
            commentList.clear();
            for(ComicComment comment : chaptersInfo.commentBests()) {
                commentList.add(new ComicReaderCommentItemViewModel(comment));
            }
//            commentAdapter.notifyDataSetChanged();
//            notifyPropertyChanged(BR.seeMoreBtnVisible);
//            notifyPropertyChanged(BR.hotCommentTextVisible);
            notifyChange();
        }

        public void loadChaptersGiveLikeData(int count, boolean isGiveLike) {
            this.count = count;
            this.isGiveLike = isGiveLike;

            notifyPropertyChanged(BR.giveLikeIcon);
            notifyPropertyChanged(BR.giveLikeText);
        }

        public void giveLike() {
            if(isGiveLike) {
                ToastHelper.showToast("您已经点过赞了！");
            } else {
                comicReaderService.giveLike(comicBookEntity.id, chaptersInfo.id);
                count += 1;
                isGiveLike = true;
                notifyPropertyChanged(BR.giveLikeIcon);
                notifyPropertyChanged(BR.giveLikeText);
            }
        }

        @Bindable
        public ArrayList<PictureResource> getPictureResourceList() {
            return chaptersInfo.pictureResourcesList;
        }

        @Bindable
        public SafeIterableMap<String, SafeIterableList<BulletScreenInfo>> getBulletScreenInfoMap() {
            return chaptersInfo.bulletScreenInfoMap();
        }

        @Bindable
        public int getFinishTipsLayoutVisible() {
            return chaptersInfo.directoryInfo().isLatest ? View.VISIBLE : View.GONE;
        }

        @Bindable
        public int getFinishTipsImage() {
            if( comicBookEntity == null) {
                return 0;
            }
            if(!chaptersInfo.directoryInfo().isLatest) {
                return 0;
            }
            return comicBookEntity.isEndState() ? R.drawable.app_comic_reader_pic_end : R.drawable.app_comic_reader_pic_continued_read;
        }

        @Bindable
        public int getGiveLikeVisible() {
            return View.VISIBLE;
        }
        @Bindable
        public CharSequence getGiveLikeText() {
            return "点赞("+count+")";
        }
        @Bindable
        public int getGiveLikeIcon() {
            return isGiveLike ? R.drawable.app_comic_reader_icon_give_like_a : R.drawable.app_comic_reader_icon_give_like_b;
        }

        @Bindable
        public int getSeeMoreBtnVisible() {
            return chaptersInfo.commentBests() == null || chaptersInfo.commentBests().length == 0 ? View.GONE : View.VISIBLE;
        }
        @Bindable
        public CharSequence getSeeMoreBtnText() {
            return "查看更多评论 >";
        }

        @Bindable
        public int getHotCommentTextVisible() {
            return chaptersInfo.commentBests() == null || chaptersInfo.commentBests().length == 0 ? View.GONE : View.VISIBLE;
        }
        @Bindable
        public int getNoCommentsPromptVisible() {
            return commentList.isEmpty() ? View.VISIBLE : View.GONE;
        }
        @Bindable
        public int getCommentListVisible() {
            return commentList.isEmpty() ? View.GONE : View.VISIBLE;
        }
        @Bindable
        public BaseAdapter getCommentAdapter() {
            return commentAdapter;
        }

        @AdapterEntityBind(viewRid = R.layout.layout_comic_reader_item_comment)
        public class ComicReaderCommentItemViewModel extends BaseObservable implements AutoVariable<LayoutComicReaderItemCommentBinding> {

            public final ComicComment comment;

            public ComicReaderCommentItemViewModel(ComicComment comment) {
                this.comment = comment;
            }

            @Override
            public void bindVariable(LayoutComicReaderItemCommentBinding viewBind) {
                viewBind.setComicReaderCommentItemViewModel(this);
            }

            public boolean isMyLike() {
                return comment.isMyLike();
            }

            /** 点赞 */
            public void giveAlike() {
                comment.likeCountUp();
                comicReaderService.voteToGiveLikeComment(comicBookEntity.id, comment.id);
                notifyPropertyChanged(BR.likeCount);
                notifyPropertyChanged(BR.likeDrawable);
            }




            @Bindable
            public int getPortraitHeadWearVisible() {
                return comment.isVip() ? View.VISIBLE : View.GONE;
            }

            @Bindable
            public String getPortraitPath() {
                return comment.userPortrait;
            }

            @Bindable
            public CharSequence getUserName() {
                return comment.userName;
            }

            @Bindable
            public String getUserNameColor() {
                return comment.isVip() ? "#ff5050" : "#777777";
            }

            @Bindable
            public CharSequence getContent() {
                return comment.content;
            }

            @Bindable
            public CharSequence getCommentTime() {
                return comment.createTime;
            }

            @Bindable
            public CharSequence getLikeCount() {
                return comment.likeCountToString();
            }

            @Bindable
            public CharSequence getReplyCount() {
                return comment.replyCountToString();
            }

            @Bindable
            public int getLikeDrawable() {
                return comment.isMyLike() ? R.drawable.app_comment_icon_give_like_a : R.drawable.app_comment_icon_give_like_b;
            }

        }

    }

}
